package com.dylan.channel.v1;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;

public class Work implements Runnable{
    Logger logger=Logger.getLogger(Work.class.getName());
    Selector selector;

    Thread thread;

    volatile  boolean  started;

    public Work() {
        selector=openSelector();
    }

    private Selector openSelector() {
        Selector wrapSelector = null;
        try {
            wrapSelector = SelectorProvider.provider().openSelector();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return wrapSelector;
    }

    @Override
    public void run() {
        while (true){
            try {
                selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    try {
                        iterator.remove();
                        if(key.isReadable()){
                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            int read = channel.read(buffer);
                            if(read==-1){
                                channel.close();
                                key.cancel();
                                break;
                            }
                            buffer.flip();
                            logger.info("接受到客户端发过来的消息:"+new String(buffer.array(), StandardCharsets.UTF_8));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel();
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }

    public  void register(SocketChannel channel){
        register0(channel);

        //startThread
        startThread();
    }

    private void startThread() {
        if(started){
            return;
        }
        started=true;
        new Thread(()->{
            thread=Thread.currentThread();
            Work.this.run();
        }).start();
    }

    private void register0(SocketChannel channel) {
        try {
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_READ);
            logger.info("接受到客户端连接:"+channel.getRemoteAddress().toString());
            ByteBuffer buffer=ByteBuffer.allocate(1024);
            buffer.put("该客户端已经连接成功".getBytes(StandardCharsets.UTF_8));
            buffer.flip();
            channel.write(buffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
